#!/bin/bash

echo -e "\033[31;1m*****[ Mongodb ] 增量恢复脚本*****\033[0m"

#### 请在此处输入关键参数，例如程序路径，账号，密码，实例端口###
command_linebin="/mongodb/mongodb-4.0.10/bin"
username="xxx"
password="xxx"
port="27017"

bkdatapath=/mongodb/backup/incremental/mongo-$port

tempPath=/mongodb/backup/incremental/tmp
####

echo -e "\033[32;1m[ 选择要恢复增量的日期(格式：年月日时分秒) ] \033[0m"
for backfile in `ls $bkdatapath`; do
    echo $backfile
done

read -p ">>>" date_bak

if [[ $date_bak == "" ]] || [[ $date_bak == '.' ]] || [[ $date_bak == '..' ]]; then
    echo -e "\033[31;1m输入不能为特殊字符.\033[0m"
    exit 1
fi


if [ -d $bkdatapath/$date_bak ]; then
    read -p "请确认是否恢复[$date_bak]增量备份[y/n]:" choice

    if [ "$choice" == "y" ]; then
        echo -e "\033[32;1m正在进行[$date_bak]增量恢复，请稍后...\033[0m"
        mkdir -p $tempPath && cp -a $bkdatapath/$date_bak/local/oplog.rs.bson $tempPath/oplog.bson

        $command_linebin/mongorestore -h localhost --port $port -u$username -p$password --authenticationDatabase "admin" --oplogReplay $tempPath

        rm -rf $tempPath

        if [ $? -eq 0 ]; then
            echo -e "\033[32;1m--------[$date_bak]增量恢复成功--------\033[0m"
        else
            echo -e "\033[31;1m恢复失败,请手动检查!\033[0m"
            exit 3
        fi
    else
        exit 2
    fi
else
    echo "\033[31;1m输入信息错误.\033[0m"
    exit 1
fi
